package scau.jump.securitytrace.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.hibernate.criterion.Property;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import scau.jump.securitytrace.service.RFIDService;
import scau.jump.securitytrace.service.exception.InvalidAntiFakeCodeException;
import scau.jump.securitytrace.service.exception.RFIDNotExistException;

import com.securitytrace.model.Address;
import com.securitytrace.model.AntiFakeCode;
import com.securitytrace.model.Product;
import com.securitytrace.model.RFID;
import com.securitytrace.model.RfidRecordedInfo;

public class RFIDServiceImpl extends HibernateDaoSupport implements RFIDService {

	public void add(RFID rfid) {
		if(rfid.getId() == null) {
			rfid.setId(UUID.randomUUID().toString());
		}
		getHibernateTemplate().save(rfid.getAntiFakeCode());
		getHibernateTemplate().save(rfid);
	}

	public RFID getById(String id) throws RFIDNotExistException {
		RFID rfid = getHibernateTemplate().get(RFID.class, id);
		if(rfid == null) {
			throw new RFIDNotExistException();
		}
		return rfid;
	}
	
	@SuppressWarnings("unchecked")
	public RFID getByAntiFakeCode(String code) throws InvalidAntiFakeCodeException {
		List<AntiFakeCode> list = getSession().createCriteria(AntiFakeCode.class).add(Property.forName("code").eq(code)).list();
		if(list == null || list.size() == 0) {
			throw new InvalidAntiFakeCodeException();
		}
		List<RFID> rfidList = getSession().createCriteria(RFID.class).add(Property.forName("antiFakeCode").eq(list.get(0))).list();
		if(rfidList == null || rfidList.size() == 0) {
			return null;
		}
		return rfidList.get(0);
	}
	
	public void addProductInfo(String rfidId, long productId) throws RFIDNotExistException {
		RFID rfid = getById(rfidId);
		Product product = getHibernateTemplate().get(Product.class, productId);
		rfid.setProduct(product);
	}
	
	public void addRFIDRecordInfo(String rfidId, long addressId) throws RFIDNotExistException {
		RfidRecordedInfo info = new RfidRecordedInfo();
		RFID rfid = getById(rfidId);
		Address address = getHibernateTemplate().get(Address.class, addressId);
		info.setAddress(address);
		info.setRfid(rfid);
		info.setRecordedDate(new Date());
		getHibernateTemplate().save(info);
	}

	public void setParent(String childId, String parentId)
			throws RFIDNotExistException {
		RFID child = getById(childId);
		RFID parent = getById(parentId);
		child.setParent(parent);
	}

	public void setParent(String[] childIds, String parentId)
			throws RFIDNotExistException {
		for(String childId : childIds) {
			setParent(childId, parentId);
		}
	}

}
